<?php
/*
* Template Name: 密码重置模板
*
* @Author: UCtheme PHP Studio
* @Author URI: http://www.uctheme.com
* @since zzdgm 1.8
*/
global $wpdb, $user_ID;
function tg_validate_url() {
	global $post;
	$page_url = esc_url(get_permalink( $post->ID ));
	$urlget = strpos($page_url, "?");
	if ($urlget === false) {
		$concate = "?";
	} else {
		$concate = "&";
	}
	return $page_url.$concate;
}

if (!$user_ID) { //block logged in users

	if(isset($_GET['key']) && $_GET['action'] == "reset_pwd") {
		$reset_key = $_GET['key'];
		$user_login = $_GET['login'];
		$user_data = $wpdb->get_row($wpdb->prepare("SELECT ID, user_login, user_email FROM $wpdb->users WHERE user_activation_key = %s AND user_login = %s", $reset_key, $user_login));
		
		$user_login = $user_data->user_login;
		$user_email = $user_data->user_email;
		
		if(!empty($reset_key) && !empty($user_data)) {
			$new_password = wp_generate_password(7, false);
				//echo $new_password; exit();
				wp_set_password( $new_password, $user_data->ID );
				//mailing reset details to the user
			$message = __('账户的新密码为:') . "\r\n\r\n";
			$message .= get_option('siteurl') . "\r\n\r\n";
			$message .= sprintf(__('用户名:%s'), $user_login) . "\r\n\r\n";
			$message .= sprintf(__('密码: %s'), $new_password) . "\r\n\r\n";
			$message .= __('你可以使用你的新密码通过下面的链接登录:  ') . get_option('siteurl')."/login" . "\r\n\r\n";
			
			if ( $message && !wp_mail($user_email, '密码重置请求', $message) ) {
				echo "<div class='error'>邮件发送失败-原因未知</div>";
				exit();
			}
			else {
				$redirect_to = get_bloginfo('url')."/login?action=reset_success";
				wp_safe_redirect($redirect_to);
				exit();
			}
		} 
		else exit('Not a Valid Key.');
		
	}
	//exit();

	if($_POST['action'] == "tg_pwd_reset"){
		if ( !wp_verify_nonce( $_POST['tg_pwd_nonce'], "tg_pwd_nonce")) {
		  exit("No trick please");
	   }  
		if(empty($_POST['user_input'])) {
			echo "<div class='error'>请输入用户名或E-mail地址</div>";
			exit();
		}
		//We shall SQL escape the input
		$user_input = $wpdb->escape(trim($_POST['user_input']));
		
		if ( strpos($user_input, '@') ) {
			$user_data = get_user_by_email($user_input);
			if(empty($user_data) || $user_data->caps[administrator] == 1) { //delete the condition $user_data->caps[administrator] == 1, if you want to allow password reset for admins also
				echo "<div class='error'>错误：无效的E-mail地址!</div>";
				exit();
			}
		}
		else {
			$user_data = get_userdatabylogin($user_input);
			if(empty($user_data) || $user_data->caps[administrator] == 1) { //delete the condition $user_data->caps[administrator] == 1, if you want to allow password reset for admins also
				echo "<div class='error'>错误：无效的用户名!</div>";
				exit();
			}
		}
		
		$user_login = $user_data->user_login;
		$user_email = $user_data->user_email;
		
		$key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
		if(empty($key)) {
			//generate reset key
			$key = wp_generate_password(20, false);
			$wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));	
		}
		
		//mailing reset details to the user
		$message = __('有人提交了重置下面账户密码的请求:') . "\r\n\r\n";
		$message .= get_option('siteurl') . "\r\n\r\n";
		$message .= sprintf(__('用户名: %s'), $user_login) . "\r\n\r\n";
		$message .= __('如果不是您本人操作，请忽略这个邮件即可.') . "\r\n\r\n";
		$message .= __('如果需要重置密码，请访问下面的链接: (点击下面链接，如果密码重置成功，您将收到另一封包含新密码的邮件，请注意查收。)') . "\r\n\r\n";
		$message .= tg_validate_url() . "action=reset_pwd&key=$key&login=" . rawurlencode($user_login) . "\r\n";
		
		if ( $message && !wp_mail($user_email, '密码重置请求', $message) ) {
			echo "<div class='error'>邮件发送失败-原因未知。</div>";
			exit();
		}
		else {
			echo "<div class='success'>我们已经在给你发送的邮件中说明了重置密码的各项事宜，请注意查收。</div>";
			exit();
		}
		
	} else { 

get_header(); ?>

<div class="container">
  <meta name='robots' content='noindex,nofollow' />
  <link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/login.css" type="text/css" media="all" />
  <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/login.js?v=201303151700"></script>
  <!-- S index Main -->
  <div class="left_main" id="left_side">
    <!--s content_out -->
    <div class="content_out">
      <div class="content">
        <div id="login">
          <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
          <p class="message">请输入您的用户名或电子邮箱地址。您会收到一封包含创建新密码链接的电子邮件。</p>
          <div id="result" align="center"  style="margin-bottom:15px; font-size:14px; color:red"></div>
          <!-- 为ajax返回结果做准备 -->
          <form name="lostpasswordform" id="lostpasswordform" action="" method="post">
            <p>
              <label for="user_login" class="findPsd" >用户名或电子邮件地址：</label>
              <input type="text" name="user_input" id="user_login" class="input" value="" size="20" tabindex="10" onFocus="this.value=''" />
            </p>
            <input type="hidden" name="action" value="tg_pwd_reset" />
            <input type="hidden" class="text" name="tg_pwd_nonce" value="<?php echo wp_create_nonce("tg_pwd_nonce"); ?>" />
            <p class="submit">
              <label for="user_login" style="width:67px;"></label>
              <input type="submit" name="submit" id="submitbtn" class="button-primary" value="获取新密码" tabindex="100" />
            </p>
          </form>
        </div>
        <div class="clear"></div>
      </div>
    </div>
  </div>
  <script type="text/javascript">    
        $("#submitbtn").submit(function() {     
            var input_data = $('#lostpasswordform').serialize();    
            $.ajax({    
                type: "POST",    
                url:  "<?php echo get_permalink( $post->ID ); ?>",    
                data: input_data,    
                success: function(msg){    
                    $('.loading').remove();    
                    $('<div>').html(msg).appendTo('div#result').hide().fadeIn('slow');    
                }    
            });    
            return false;    
        });    
        </script>
  <!-- E Main -->
  <!--s right -->
  <?php get_sidebar();?>
  <!-- E Sidebar -->
  <div class="clear"></div>
  <?php endwhile; else : ?>
  <h2>
    <?php _e('没有找到'); ?>
  </h2>
  <?php endif; ?>
</div>
<?php get_sidebar();?>
<?php

get_footer();
	}
}
else {
	wp_redirect( home_url() ); exit;
	//redirect logged in user to home page
}
?>
